package com.it.schoolbookshop_back.controller.admin;

import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.service.AdminBookManageService;
import com.it.schoolbookshop_back.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminBookManageController {

    @Autowired
    private AdminBookManageService adminBookManageService;
    
    /**
     * 管理员删除书籍
     * 
     * @param bookId 书籍ID
     * @return 删除结果
     */
    @DeleteMapping("/book/{book_id}")
    public Result<Object> deleteBook(@PathVariable("book_id") Integer bookId) {
        try {
            // 验证是否是管理员
            String userRole = UserContext.getRole();
            if (userRole == null || !userRole.equalsIgnoreCase("ADMIN")) {
                return Result.forbidden();
            }
            
            // 调用服务删除书籍
            boolean success = adminBookManageService.deleteBook(bookId);
            
            if (success) {
                return Result.success("删除书籍成功", null);
            } else {
                return Result.failed("删除书籍失败");
            }
        } catch (IllegalArgumentException e) {
            // 参数验证异常
            return Result.validateFailed(e.getMessage());
        } catch (Exception e) {
            // 其他异常
            log.error("删除书籍异常", e);
            return Result.failed("删除书籍失败: " + e.getMessage());
        }
    }
}
